import 'package:collection/collection.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:hxdj/common/components/my_keep_alive.dart';
import 'package:hxdj/common/my_optimize_utils.dart';
import 'package:hxdj/message/rongcloud/chat/rc_chat_global_viewmodel.dart';
import 'package:hxdj/message/rongcloud/rc_chat/model/rc_chat_model.dart';
import 'package:hxdj/message/rongcloud/chat/rc_chat_separate_view_model.dart';
import 'package:provider/provider.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

enum LoadingPlace {
  none,
  top,
  bottom,
}

enum ScrollType { toIndex, toIndexBegin }

class TIMUIKitHistoryMessageList extends StatefulWidget {
  /// message list
  final List<ChatMessageBaseModel?> messageList;

  /// use for build message item
  final Widget Function(BuildContext, ChatMessageBaseModel?)? itemBuilder;

  /// use for load more message
  final Future<void> Function(int?) onLoadMore;

  final RCChatSeparateViewModel model;

  const TIMUIKitHistoryMessageList({
    super.key,
    required this.model,
    required this.messageList,
    this.itemBuilder,
    required this.onLoadMore,
  });

  @override
  State<StatefulWidget> createState() => _TIMUIKitHistoryMessageListState();
}

class _TIMUIKitHistoryMessageListState extends State<TIMUIKitHistoryMessageList> {
  String findingSeq = "";
  late AutoScrollController _autoScrollController;
  LoadingPlace loadingPlace = LoadingPlace.none;

  @override
  void initState() {
    super.initState();
    _autoScrollController = AutoScrollController();
  }

  @override
  Widget build(BuildContext context) {
    // center key should generate everytime when build method called.
    final GlobalKey centerKey = GlobalKey();

    if (widget.messageList.isEmpty) {
      return Container();
    }

    final messageList = widget.messageList;

    final throttleFunctionWithMsgID = MyOptimizeUtils.throttle((int msgTimestamp) async {
      await widget.onLoadMore(msgTimestamp);
    }, 200);

    String getMessageIdentifier(ChatMessageBaseModel? message, int index) {
      return "${message?.messageId} - ${message?.sentTime} - ${message?.messageUId}";
    }

    Widget getMessageItemBuilder(ChatMessageBaseModel? messageItem) {
      if (widget.itemBuilder != null) {
        return widget.itemBuilder!(context, messageItem);
      }
      return Container();
    }

    return Stack(
      alignment: Alignment.topCenter,
      children: [
        Scrollbar(
            controller: _autoScrollController,
            child: CustomScrollView(
              center: null,
              cacheExtent: 500,
              dragStartBehavior: DragStartBehavior.start,
              keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.manual,
              clipBehavior: Clip.hardEdge,
              reverse: true,
              shrinkWrap: true,
              controller: _autoScrollController,
              slivers: [
                SliverPadding(
                  padding: EdgeInsets.zero,
                  key: centerKey,
                ),
                SliverPadding(
                  padding: EdgeInsets.zero,
                  sliver: Selector<RCChatSeparateViewModel, bool>(
                    selector: (context, model) {
                      return model.haveMoreData;
                    },
                    shouldRebuild: (previous, next) {
                      return previous != next;
                    },
                    builder: (context, haveMoreData, child) {
                      return SliverList(
                          delegate: SliverChildBuilderDelegate(
                              (BuildContext context, int index) {
                                print("是否还有数据 == ${haveMoreData}");

                             

                                final messageItem = messageList[index];
                                if (index == messageList.length - 1) {
                                  if (haveMoreData) {
                                    final ChatMessageBaseModel? lastMessage = messageList.last;
                                    throttleFunctionWithMsgID(lastMessage!.sentTime!);
                                  }
                                  return Column(
                                    children: [
                                      haveMoreData
                                          ? const Center(
                                              child: CupertinoActivityIndicator(
                                              color: Colors.grey,
                                              radius: 10,
                                            ))
                                          : Container(),
                                      AutoScrollTag(
                                        controller: _autoScrollController,
                                        index: -index,
                                        key: ValueKey(getMessageIdentifier(messageItem, index)),
                                        highlightColor: Colors.black.withOpacity(0.1),
                                        child: MyKeepAliveWrapper(
                                            keepAlive: false, child: getMessageItemBuilder(messageItem)),
                                      ),
                                    ],
                                  );
                                }
                                return AutoScrollTag(
                                  controller: _autoScrollController,
                                  index: -index,
                                  key: ValueKey(getMessageIdentifier(messageItem, index)),
                                  highlightColor: Colors.black.withOpacity(0.1),
                                  child:
                                      MyKeepAliveWrapper(keepAlive: false, child: getMessageItemBuilder(messageItem)),
                                );
                              },
                              childCount: messageList.length,
                              findChildIndexCallback: (Key key) {
                                final ValueKey<String> valueKey = key as ValueKey<String>;
                                final String data = valueKey.value;
                                final int index =
                                    messageList.indexWhere((element) => getMessageIdentifier(element, 0) == data);
                                return index > -1 ? index : null;
                              }));
                    },
                  ),
                ),
              ],
            )),
      ],
    );
  }
}

class TIMUIKitHistoryMessageListSelector extends StatelessWidget {
  final Widget Function(BuildContext, List<ChatMessageBaseModel?>, Widget?) builder;
  final String conversationID;

  const TIMUIKitHistoryMessageListSelector({super.key, required this.builder, required this.conversationID});

  @override
  Widget build(BuildContext context) {
    return Selector<RCChatGlobalModel, List<ChatMessageBaseModel?>>(
        builder: builder,
        shouldRebuild: (previous, next) {
          final isEquals = const DeepCollectionEquality.unordered().equals(previous, next);
          debugPrint("isEquals == ${isEquals}");
          return !isEquals;
        },
        selector: (context, model) {
          final messageList = model.getMessageList(conversationID) ?? [];
          return messageList;
        });
  }
}
